package com.lgx.mall.web.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lgx.common.alipay.util.UtilDate;
import com.lgx.common.entity.CityDictonary;
import com.lgx.common.entity.Dictionary;
import com.lgx.common.exception.DataException;
import com.lgx.common.service.ICityDictonaryService;
import com.lgx.common.util.ImageConstants;
import com.lgx.common.web.Constants;
import com.lgx.common.web.util.ArrayUtils;
import com.lgx.common.web.util.DictUtils;
import com.lgx.common.web.util.EscapeUtils;
import com.lgx.mall.basic.entity.Address;
import com.lgx.mall.basic.service.IAddressService;
import com.lgx.mall.basic.service.IFareService;
import com.lgx.mall.business.entity.Order;
import com.lgx.mall.business.entity.OrderDetail;
import com.lgx.mall.business.service.IOrderDetailService;
import com.lgx.mall.business.service.IOrderService;
import com.lgx.mall.core.entity.Product;
import com.lgx.mall.core.service.IProductService;
import com.lgx.right.entity.Card;
import com.lgx.right.entity.User;
import com.lgx.right.service.ICardService;

/**
 * 
 * 购物车
 * @author acer
 *
 */
@Controller
@RequestMapping("/cart")
public class CartController {

	@Autowired
	private IOrderService orderService;
	
	@Autowired
	private IOrderDetailService orderDetailService;
	
	@Autowired
	private IAddressService addressService;      //默认收货地址
	
	@Autowired
	private ICityDictonaryService cityDictonaryService;  //收货地址
	
	@Autowired
	private IProductService productService;            //商品
	
	@Autowired
	private IFareService fareservice;
	
	@Autowired
	private ICardService cardService;

	public IFareService getFareservice() {
		return fareservice;
	}

	public void setFareservice(IFareService fareservice) {
		this.fareservice = fareservice;
	}

	public ICardService getCardService() {
		return cardService;
	}

	public void setCardService(ICardService cardService) {
		this.cardService = cardService;
	}

	public IProductService getProductService() {
		return productService;
	}

	public void setProductService(IProductService productService) {
		this.productService = productService;
	}

	public ICityDictonaryService getCityDictonaryService() {
		return cityDictonaryService;
	}

	public void setCityDictonaryService(ICityDictonaryService cityDictonaryService) {
		this.cityDictonaryService = cityDictonaryService;
	}

	public IAddressService getAddressService() {
		return addressService;
	}

	public void setAddressService(IAddressService addressService) {
		this.addressService = addressService;
	}

	public IOrderDetailService getOrderDetailService() {
		return orderDetailService;
	}

	public void setOrderDetailService(IOrderDetailService orderDetailService) {
		this.orderDetailService = orderDetailService;
	}

	public IOrderService getOrderService() {
		return orderService;
	}

	public void setOrderService(IOrderService orderService) {
		this.orderService = orderService;
	}
	
	@RequestMapping("/add/product.htm")
	@ResponseBody
	public String addCart(HttpServletRequest request,HttpServletResponse response){
		String path = request.getContextPath();
		String basePath = request.getScheme() + "://"
				+ request.getServerName() + ":" + request.getServerPort()
				+ path + "/";
		
		String img_server_url = (String)request.getServletContext().getAttribute(ImageConstants.IMG_SERVER_URL);
		
		String repeat = request.getParameter("repeat");
		String flag = request.getParameter("flag");
		String userId = request.getParameter("userId");
		String productId = request.getParameter("productId");
		
		User onlineUser = (User) request.getSession().getAttribute(Constants.LOGIN_USER);
		
		if("0".equals(userId)||StringUtils.isEmpty(userId)) userId = onlineUser.getId()+"";
		
		Order order = this.orderService.findOrderByUserId(Long.parseLong(userId));
		
		StringBuffer sb = new StringBuffer();
		String result = this.orderDetailService.checkOrderDetail(order.getId(), Long.parseLong(productId));
		
		if("false".equals(repeat)){
			if("2".equals(result)){
				sb.append("var submit = function (v, h, f) {");
				sb.append("    if (v == 'ok') {");
				sb.append("    		addProductToCard(true);");
				sb.append("     }");
				sb.append("    else if (v == 'cancel') {");
				sb.append("    		location.reload();");
				sb.append("   }");
				sb.append("    return true;");
				sb.append(" };");
				sb.append(" $.jBox.confirm(\"购物车中已有是否继续？\", \"提示\", submit);");
				return sb.toString();
			}else if("3".equals(result)){
				sb.append("$.jBox.prompt(\"该类商品已购卖数已超，请选择其它商品！\", '提示', 'info');");
				return sb.toString();
			}
		}
		
		order = this.orderService.addOrderDetail(Long.parseLong(userId), productId, "com.lgx.mall.core.entity.Product", "");
		
		List<OrderDetail> details = this.orderDetailService.findOrderDetailList(order.getId());
		
		if(details.size() == 0){
			sb.append("$(\"#mini-cart-count\").html(0);");
			sb.append("$(\"#J-mini-cart-full\").hide();");
			sb.append("$(\"#J-mini-cart-empty\").show();");
			
			return sb.toString();
		}
		
		sb.append("$(\"#J-mini-cart-full\").show();");
		sb.append("$(\"#J-mini-cart-empty\").hide();");
		
		sb.append("$(\"#mini-cart-count\").html("+order.getAmount()+");");
		
		StringBuffer sb2 = new StringBuffer();
		for(OrderDetail detail : details){
			sb2.append("<dl class=\"clearfix\" id=\"dl_"+detail.getId()+"\"> ");
			sb2.append("<dt class=\"img\"><a href=\""+basePath+detail.getEntityUrl()+"\"><img width=\"54\" height=\"54\" src=\""+img_server_url+"/"+detail.getEntityImg()+"\"/></a></dt> ");
			sb2.append("<dd class=\"n\"><a href=\""+basePath+detail.getEntityUrl()+"\">"+detail.getEntityName()+"<br/></a></dd>");
			sb2.append("<dd class=\"num\">");
			sb2.append("	<em class=\"price\">"+detail.getPrice()+" x "+detail.getAmount()+"</em>");
			sb2.append("	<span class=\"act del\"><a href=\"javascript:removeCart("+detail.getId()+")\">删除</a></span>");
			sb2.append("</dd>");
			sb2.append("</dl>");
		}
		sb2.append("<ul class=\"statistics\"><li class=\"collect\"><a href=\"#\"><b></b>收藏商品</a></li><li class=\"total\" id=\"optotal\"><em>"+order.getAmount()+"</em>件商品 总计<em>"+order.getScore()+"</em><span>积分</span></li></ul>");
		sb2.append("<div class=\"mini-cart-act\"><a href=\"\" class=\"checkout\">去结算</a><a href=\""+basePath + "member/index.htm?url=cart/list.htm" +"\" class=\"check\">查看购物车&gt;&gt;</a></div>");
		sb.append("$(\"#J-mini-cart-full\").html('"+sb2.toString()+"');");
		
		sb.append("location.reload();");
		
		if("false".equals(flag)){
			sb.append("document.URL='';");
		}
		
		sb.append("$.jBox.success(\"成功加入购物车\", \"提示\");");
		
		return sb.toString();
	}
	
	@RequestMapping("/del.htm")
	@ResponseBody
	public String delDetail(HttpServletRequest request,HttpServletResponse response){
		String detailId = request.getParameter("detailId");
		String userId = request.getParameter("userId");
		
		OrderDetail detail = this.orderDetailService.findOrderDetailById(Long.parseLong(detailId));
		
		double price = detail.getPrice();
		int amount = detail.getAmount();
		
		this.orderDetailService.deleteOrderDetail(Long.parseLong(detailId));
		
		Order order = this.orderService.findOrderByUserId(Long.parseLong(userId));
		
		order.setScore(order.getScore()-price*amount);
		order.setAmount(order.getAmount()-amount);
		
		this.orderService.updateOrder(order);
		
		StringBuffer sb = new StringBuffer();
		
		sb.append("location.reload();");
		
		return sb.toString();
	}
	
	/**
	 * 加载购物车数据
	 * 因为如果有url
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/list.htm")
	public String list(HttpServletRequest request,HttpServletResponse response){
		//查询这个用户对应的orderID
		User onlineUser = (User) request.getSession().getAttribute(Constants.LOGIN_USER);
		if(onlineUser!=null){
			//根据用户id查询orderId
			Order order = orderService.findOrderByUserId(onlineUser.getId());
			if(order!=null){ //找到了这个用户对应的订单号
				List<OrderDetail> orderDetails = orderDetailService.findOrderDetailList(order.getId());
				if(orderDetails.size()>0){
					request.setAttribute("orderDetails", orderDetails);
				}
				request.setAttribute("order", order);
			}
		}
		
		return "member/cart/cartMgr";
	}
	
	/**
	 * 删除购物车中的某个商品
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/delete.htm")
	@ResponseBody
	public String delete(HttpServletRequest request,HttpServletResponse response){
		String id = request.getParameter("id");
		//根据id查询到这个商品是否存在于订单中
		OrderDetail oDetail = this.orderDetailService.findOrderDetailById(Long.parseLong(id));
		//通过此件商品对应的订单id得到这个订单,并在其中修改数量
		Order order = this.orderService.findOrderById(oDetail.getOrder().getId());
		int amount = oDetail.getAmount();  //amount为0代表根本就没有执行操作
		Double price = oDetail.getPrice();
		if(oDetail != null && order != null){
			try {
				this.orderDetailService.deleteOrderDetail(oDetail);  
				order.setAmount(order.getAmount() - amount);
				order.setScore(order.getScore() - (price*amount));
				this.orderService.updateOrder(order);  //待解决bug
			} catch (Exception e) {
				return "2";   //删除失败
			}
		}else{
			return "1";    //商品不存在
		}
			
		return "0";  //删除成功
	}
	
	/**
	 * 清空登陆者现在的购物车
	 * 一个用户只有一个购物车，当提交后，购物车转变为订单
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/deleteAll.htm")
	@ResponseBody
	public String deleteAll(HttpServletRequest request,HttpServletResponse response){
		User onlineUser = (User) request.getSession().getAttribute(Constants.LOGIN_USER);
		if(onlineUser!=null){
			Order order = orderService.findOrderByUserId(onlineUser.getId());//先找出这个用户的购物车
			if(order!=null){
				List<OrderDetail> orderDetails = orderDetailService.findOrderDetailList(order.getId());//有购物车存在，取得里面的商品集合并循环删除
				for (OrderDetail odl : orderDetails) {
					try {
						orderDetailService.deleteOrderDetail(odl);
					} catch (Exception e) {
						return "1";   //删除失败
					}
				}
				//循环删除没有出现异常，把购物车对象的总价、商品数量清空
				order.setAmount(0);
				order.setScore(0.0);
				try {
					orderService.updateOrder(order);
				} catch (Exception e) {
					return "1";   //删除失败
				}
			}
		}
		return "0";   //删除成功
	}
	
	
	
	/**
	 * 购物车提交生成订单，此次跳转到确认页面
	 * 确认页面中需要显示的数据，也为需要加载的数据
	 * 1、默认收货地址，没有默认收货地址，就需要给用户以提示并添加一个新的收货地址，这个收货地址将成为默认地址
	 * 2、配送方式，没有默认配送方式，即给定编辑配送方式
	 * 3、购物车中的商品信息
	 * 4、结算信息 ，结算信息 = 订单总金额+运费（显示的时候，积分和运费分开）
	 */
	@RequestMapping("/orderConfirm.htm")
	public String orderConfirm(HttpServletRequest request,HttpServletResponse response){
		//接受购物车id
		String orderId = request.getParameter("orderId");
		List<OrderDetail> orderDetails = new ArrayList<OrderDetail>();
		
		User onlineUser = (User) request.getSession().getAttribute(Constants.LOGIN_USER);
		//加载默认地址,并提供地址的省级市联查询(参数 1 是表示为默认地址)
		Address address = this.addressService.findAddressList(onlineUser.getId(),1).get(0);
		List<Address> ads = this.addressService.findAddressList(onlineUser.getId());
		if(address!=null){
			request.setAttribute("address", address);
		}
		if(ads.size()>0){
			request.setAttribute("ads", ads);
		}
		
		String fareway ="";
		
		String[] fs = {};
		
		//查询订单以及配送方式
		Order order = this.orderService.findOrderById(Long.parseLong(orderId));
		if(order!=null && order.getStatus() == 0){
			orderDetails = this.orderDetailService.findOrderDetailList(order.getId());
			for (OrderDetail ods : orderDetails) {
				Product product = this.productService.findProductById(ods.getEntityId());
				if(product!= null){
					fareway = product.getFareway();
					fs = ArrayUtils.intersect(fs, fareway.split(","));  //取订单中商品配送方式的交集
				}
			}
			
			for(String f : fs){
				if(!StringUtils.isEmpty(fareway))fareway +=",";
				fareway +=f;
			}
			
			//改变配送方式，以便加载
			order.setFareway(fareway);
		}
		
		request.setAttribute("order", order);
		
		//得到配送方式数据字典
		List<Dictionary> fareways = DictUtils.getDictListByKind(DictUtils.PRODUCT_FAREWAY);
		request.setAttribute("fareways", fareways);
		
		//根据查询到的购物车id找到旗下的全部商品
		if(orderDetails.size()>0){
			request.setAttribute("orderDetails", orderDetails);
		}
		
		//收货地址设置省级市联加载
		List<CityDictonary> provinces = this.cityDictonaryService.findCityDictonaryList("province","");
		request.setAttribute("provinces", provinces);
		
		return "member/cart/cartSettlement";
	}
	
	/**
	 * 修改支付方式信息
	 * 修改后重新计算运费，并返回运费数据加以显示
	 */
	@RequestMapping("/farewayChange.htm")
	@ResponseBody
	public String farewayChange(HttpServletRequest request,HttpServletResponse response){
		//接受新的支付方式
		String farewayValue = request.getParameter("farewayValue");
		
		String orderId = request.getParameter("orderId");

		String addressId = request.getParameter("addressId");
		
		//计算运费
		//先统计这个订单内全部商品的重量
		double farePrice = 0;
		//查询订单以及配送方式,跟据订单的地址计算运费
		Order order = this.orderService.findOrderById(Long.parseLong(orderId));
		if("1".equals(farewayValue)){
			if(order!=null){
				List<OrderDetail> orderDetails = this.orderDetailService.findOrderDetailList(order.getId());
				for (OrderDetail ods : orderDetails) {
					Product product = this.productService.findProductById(ods.getEntityId());
					if(product!= null){
						farePrice += product.getWeight()*ods.getAmount();
					}
				}
				
				Address address = this.addressService.findAddressById(Long.parseLong(addressId));
				farePrice = this.fareservice.calculationOfShippingCosts(Constants.FROM_CITY,address.getProvince(), address.getCity(),address.getRegion(), farePrice,order.getAmount());
			}
		}
		
		return farePrice + "";   //成功
	}
	
	/**
	 * 提交订单时的积分判断
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/scoreDecide.htm")
	@ResponseBody
	public String scoreDecide(HttpServletRequest request,HttpServletResponse response){
		String orderId = request.getParameter("orderId");
		if(!StringUtils.isEmpty(orderId))orderId = EscapeUtils.unescape(orderId);
		
		Order order = this.orderService.findOrderById(Long.parseLong(orderId));
		if(order.getScore() > order.getUser().getCard().getScore()){   //如果订单中的积分比这个用户会员卡中的积分要多，表示支付积分不够
			return "0";   //积分不足
		}
		return "1";
	}
	
	/**
	 * 提交订单
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/submitOrder.htm")
	public String submitOrder(HttpServletRequest request,HttpServletResponse response){
		String orderId = request.getParameter("orderId");
		String addressId = request.getParameter("addressId");
		String fareway = request.getParameter("fareway");
		String fare = request.getParameter("fare");
		
		if(StringUtils.isEmpty(fare))fare = "0";
		
		Order order = this.orderService.findOrderById(Long.parseLong(orderId));
		//提交订单
		//产生订单号
		String orderNo = UtilDate.getOrderNum();
		order.setOrderNo(orderNo);
		
		order.setFareway(fareway);
		order.setFare(Double.parseDouble(fare));
		
		Address address = this.addressService.findAddressById(Long.parseLong(addressId));
		
		order.setProvince(address.getProvince());
		order.setCity(address.getCity());
		order.setRegion(address.getRegion());
		order.setAddress(address.getAddress());
		order.setZipcode(address.getZipcode());
		order.setConsigneeName(address.getName());
		order.setConsigneeTel(address.getTel());
		order.setConcludeTime(new Date());
		
		//根据订单id找出商品集合
		List<OrderDetail> oDetails = this.orderDetailService.findOrderDetailList(order.getId());
		
		//非支付宝情况
		if(!"1".equals(fareway)){
			//扣除用户积分
			Card card = order.getUser().getCard();
			card.setScore(card.getScore()-order.getScore());
			try {
				this.cardService.updateCard(card);
			} catch (DataException e) {
				e.printStackTrace();
			}
			
			//修改商品的库存
			for(OrderDetail detail : oDetails){
				if("com.lgx.mall.core.entity.Product".equals(detail.getEntityType())){
					this.productService.modifyProductInventory(detail.getEntityId(), detail.getAmount(), "-");
				}
			}
			
			order.setPayTime(new Date());
		}
		order.setStatus(1);
		
		this.orderService.updateOrder(order);
		
		request.setAttribute("order", order);
		
		request.setAttribute("oDetails", oDetails);
		return "member/cart/orderSuccess";
	}
	
	/**
	 * 购物车收货地址加载
	 */
	@RequestMapping("/loadAddress.htm")
	@ResponseBody
	public String loadAddress(HttpServletRequest request,HttpServletResponse response){
		String id = request.getParameter("addressId");
		Address address = this.addressService.findAddressById(Long.parseLong(id));
		StringBuilder result = new StringBuilder();
		if(address!=null){
			result.append(String.valueOf(address.getId()) +"|");   //id,取值下标0
			result.append(address.getName()+"|");                  //收货人姓名，取值下标1
			result.append(address.getProvince()+"|");              //省份，取值下标2
			result.append(address.getAddressAll()+"|");            //完整地址，取值下标3
			result.append(address.getTel()+"|");                   //手机号码，取值下标4
			result.append(address.getZipcode());                   //邮编，取值下标5
		}
		return result.toString();
	}
	
	
	/**
	 * 处理重新支付情况下的跳转
	 */
	@RequestMapping("/continueOrder.htm")
	public String continueOrder(HttpServletRequest request,HttpServletResponse response){
		//接受订单id
		String orderId = request.getParameter("orderId");
		//查找订单
		Order order = this.orderService.findOrderById(Long.parseLong(orderId));
		
		if(order!= null){
			request.setAttribute("order", order);
			//根据订单id找出商品集合
			List<OrderDetail> oDetails = this.orderDetailService.findOrderDetailList(order.getId());
			request.setAttribute("oDetails", oDetails);
		}
		return "member/cart/orderSuccess";
	}
	
	
}
